package com.sensetime.stlivenesslibrary.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sensetime.stlivenesslibrary.LivenessDetector;
import com.sensetime.stlivenesslibrary.LivenessDetector.Motion;
import com.sensetime.stlivenesslibrary.R;
import com.sensetime.stlivenesslibrary.STFinanceJNI;
import com.sensetime.stlivenesslibrary.util.Constants;
import com.sensetime.stlivenesslibrary.util.DataController;
import com.sensetime.stlivenesslibrary.view.CircleTimeView;
import com.sensetime.stlivenesslibrary.view.LinkfaceAlertDialog;
import com.sensetime.stlivenesslibrary.view.TimeViewContoller;
import com.sensetime.stlivenesslibrary.view.TimeViewContoller.CallBack;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@SuppressLint("NewApi")
public class LivenessActivity extends Activity {
    /**
     * 加载库文件出现错误
     */
    public static final  int    RESULT_CREATE_HANDLE_ERROR                = 1001;
    /**
     * 无法访问摄像头，没有权限或摄像头被占用
     */
    public static final  int    RESULT_CAMERA_ERROR_NOPRERMISSION_OR_USED = 2;
    /**
     * 内部错误
     */
    public static final  int    RESULT_INTERNAL_ERROR                     = 3;
    /**
     * 传入保存结果的文件路径
     */
    public static        String EXTRA_RESULT_PATH                         = "com.sensetime.liveness.resultPath";
    /**
     * 传入活体检测的动作序列
     */
    public static final  String EXTRA_MOTION_SEQUENCE                     = "com.sensetime.liveness.motionSequence";
    /**
     * 获取info信息
     */
    public static final  String EXTRA_INFO                                = "com.sensetime.liveness.info";
    /**
     * 是否打开语音提示
     */
    public static final  String SOUND_NOTICE                              = "soundNotice";
    /**
     *  输出类型
     */
    public static final  String OUTTYPE                                   = "outType";
    /**
     * 设置复杂度
     */
    public static final  String COMPLEXITY                                = "complexity";
    public static        String SEQUENCE_JSON                             = "sequence_json";
    public static        String OUTPUT_TYPE                               = "";
    private static final int    CURRENT_ANIMATION                         = -1;
    private ImageView           mImageView;
    private TextView            mNoteTextView;
    private Context             mContext;
    private LinkfaceAlertDialog mDialog;
    private CircleTimeView      mTimeView;
    //	private Button mStartButton;
    private boolean mIsStart = false, soundNoticeOrNot = true;
    private FaceOverlapFragment mFragment;
    private RelativeLayout      mNoticeView;
    private TimeViewContoller   mTimeViewContoller;
    //	private ImageView mMaskIm ageView;
    private Bundle              bundle;
    private MediaPlayer mediaPlayer = null;
    private String[]    mDetectList = null;
    private Motion[]    mMotionList = null;
    private ImageButton soundPlayBtn, returnBtn;
    private ViewGroup viewGroup;
    private View      animFrame;
    private             int           currentDetectStep  = 0;
    private             SensorManager sm                 = null;
    public static final String        LIVENESS_FILE_NAME = "livenessResult";
    private RelativeLayout waitDetectView;
    private LinearLayout   noticeLinearLayout;
    private boolean pop = false;
    int[] defaultImageResource = {R.drawable.linkface_pic_one, R.drawable.linkface_pic_two,
            R.drawable.linkface_pic_three, R.drawable.linkface_pic_four, R.drawable.linkface_pic_five};
    int[] imageResource        = {R.drawable.linkface_pic_one, R.drawable.linkface_pic_two,
            R.drawable.linkface_pic_three, R.drawable.linkface_pic_four, R.drawable.linkface_pic_five};
    int[] imageResourceSolid   = {R.drawable.linkface_pic_onesolid, R.drawable.linkface_pic_twosolid,
            R.drawable.linkface_pic_threesolid, R.drawable.linkface_pic_foursolid, R.drawable.linkface_pic_fivesolid};
    private FaceOverlapFragment.OnLivenessCallBack listenerCallBack = new FaceOverlapFragment.OnLivenessCallBack() {
        @Override
        public void onLivenessDetect(final int value, final int status) {
            onLivenessDetectCallBack(value, status);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.linkface_activity_liveness);
        soundPlayBtn = (ImageButton) findViewById(R.id.linkface_sound_play_btn);
        mContext = this;
        bundle = getIntent().getExtras();
        mDetectList = DataController.getDetectActionOrder(bundle.getString(LivenessActivity.EXTRA_MOTION_SEQUENCE));
        mMotionList = DataController.getMctionOrder(bundle.getString(LivenessActivity.EXTRA_MOTION_SEQUENCE));
        EXTRA_RESULT_PATH = bundle.getString(LivenessActivity.EXTRA_RESULT_PATH);

        if (EXTRA_RESULT_PATH == null) {
            EXTRA_RESULT_PATH = Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "liveness" + File.separator;
        }
        File livenessFolder = new File(EXTRA_RESULT_PATH);
        if (!livenessFolder.exists()) {
            livenessFolder.mkdirs();
            ;
        }
        OUTPUT_TYPE = bundle.getString(Constants.OUTTYPE);
        soundNoticeOrNot = bundle.getBoolean(LivenessActivity.SOUND_NOTICE);
        if (soundNoticeOrNot) {
            soundPlayBtn.setBackgroundResource(R.drawable.linkface_icon_voice);
        } else {
            soundPlayBtn.setBackgroundResource(R.drawable.linkface_icon_novoice);
        }
        soundPlayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (soundNoticeOrNot) {
                    if (mediaPlayer != null) {
                        mediaPlayer.stop();
                        mediaPlayer.reset();
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                    soundPlayBtn.setBackgroundResource(R.drawable.linkface_icon_novoice);
                    soundNoticeOrNot = false;
                } else {
                    soundPlayBtn.setBackgroundResource(R.drawable.linkface_icon_voice);
                    soundNoticeOrNot = true;
                    playSoundNotice(currentDetectStep);
                }
            }
        });
        returnBtn = (ImageButton) findViewById(R.id.linkface_return_btn);
        returnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        viewGroup = (ViewGroup) findViewById(R.id.viewGroup);
        if (mDetectList.length >= 1
                && mDetectList.length <= imageResource.length) {
            for (int i = 0; i < mDetectList.length; i++) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
                imageView.setImageResource(imageResource[i]);
                viewGroup.addView(imageView);
            }
        } else if (mDetectList.length > imageResource.length) {
            for (int i = 0; i < imageResource.length; i++) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
                imageView.setImageResource(imageResource[i]);
                viewGroup.addView(imageView);
            }
        }
        setLivenessState(true);
        animFrame = findViewById(R.id.anim_frame);
        animFrame.setVisibility(View.INVISIBLE);
        initView();
        waitDetectView = (RelativeLayout) findViewById(R.id.wait_time_notice);
        waitDetectView.setVisibility(View.VISIBLE);
        noticeLinearLayout = (LinearLayout) findViewById(R.id.noticeLinearLayout);
        noticeLinearLayout.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        sm.unregisterListener(sensorEventListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isDialogShowing()) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
        }
        sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
        sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_UI);
        sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_GRAVITY), SensorManager.SENSOR_DELAY_UI);
        sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_UI);
        if (pop) {
            showDialog(getStringWithID(R.string.track_missed_dialog_title), getStringWithID(R.string.track_missed_dialog_msg));
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        pop = mIsStart;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mFragment != null) {
            mFragment.registerLivenessDetectCallback(null);
            mFragment = null;
        }
        if (mTimeViewContoller != null) {
            mTimeViewContoller.setCallBack(null);
            mTimeViewContoller = null;
        }
    }

    private void initView() {
        mNoticeView = (RelativeLayout) findViewById(R.id.noticeView);
        mImageView = (ImageView) findViewById(R.id.image);
        mNoteTextView = (TextView) findViewById(R.id.noteText);
        mTimeView = (CircleTimeView) findViewById(R.id.time_view);
        mTimeViewContoller = new TimeViewContoller(mTimeView);
        mFragment = (FaceOverlapFragment) getFragmentManager()
                .findFragmentById(R.id.overlapFragment);
        mFragment.registerLivenessDetectCallback(listenerCallBack);
        mIsStart = true;
        setLivenessState(false);
    }

    private String getStringWithID(int id) {
        return getResources().getString(id);
    }

    private void startAnimation(int animation) {
        if (animation != CURRENT_ANIMATION) {
            mImageView.setImageResource(animation);
            if (isDialogShowing()) {
                return;
            }
        }
        mTimeViewContoller.start();
        mTimeViewContoller.setCallBack(new CallBack() {
            @Override
            public void onTimeEnd() {
                mFragment.registerLivenessDetectCallback(null);
                if (null != mFragment.mDetector) {
                    try {
                        synchronized (mFragment) {
                            mFragment.stopLiveness();
                            mFragment.mDetector.end();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mFragment.startAddSequentialInfo = false;
                    saveEncryFile(mFragment.getLivenessResult());
                    mFragment.mDetector.destroy();
                    try {
                        mFragment.mDetector.finalize();
                    } catch (Throwable e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    mFragment.mDetector = null;
                }
                showDialog(getStringWithID(R.string.time_out_dialog_title),
                        getStringWithID(R.string.time_out_dialog_msg));
            }
        });
        AnimationDrawable animationDrawable = (AnimationDrawable) mImageView
                .getDrawable();
        animationDrawable.start();
    }

    private void setLivenessState(boolean pause) {
        if (null == mFragment) {
            return;
        }
        if (pause) {
            mFragment.stopLiveness();
        } else {
            mFragment.startLiveness();
        }
    }

    private void onLivenessDetectCallBack(final int value, final int status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!mIsStart) {
                    return;
                }
                currentDetectStep = status + 1;
                if (value == Motion.BLINK.getValue()) {
                    updateUi(R.string.note_blink, R.drawable.linkface_blink, status + 1);
                } else if (value == Motion.MOUTH.getValue()) {
                    updateUi(R.string.note_mouth, R.drawable.linkface_mouth, status + 1);
                } else if (value == Motion.NOD.getValue()) {
                    updateUi(R.string.note_nod, R.drawable.linkface_nod, status + 1);
                } else if (value == Motion.YAW.getValue()) {
                    updateUi(R.string.note_yaw, R.drawable.linkface_yaw, status + 1);
                } else if (value == Constants.LIVENESS_SUCCESS) {
                    updateTheLastStepUI(viewGroup);
                    saveFinalEncryFile(mFragment.getLivenessResult());
                } else if (value == Constants.LIVENESS_TRACKING_MISSED) {
                    showDialog(getStringWithID(R.string.track_missed_dialog_title), getStringWithID(R.string.track_missed_dialog_msg));
                } else if (value == Constants.LIVENESS_TIME_OUT) {
                    showDialog(getStringWithID(R.string.time_out_dialog_title), getStringWithID(R.string.time_out_dialog_msg));
                } else if (value == Constants.DETECT_BEGIN_WAIT) {
                    showDetectWaitUI();
                } else if (value == Constants.DETECT_END_WAIT) {
                    removeDetectWaitUI();
                }
            }
        });
    }

    private void showDetectWaitUI() {
        waitDetectView.setVisibility(View.VISIBLE);
        mIsStart = true;
        setLivenessState(true);
        if (mTimeViewContoller != null) {
            mTimeViewContoller.setCallBack(null);
        }
        noticeLinearLayout.setVisibility(View.INVISIBLE);
    }

    private void removeDetectWaitUI() {
        waitDetectView.setVisibility(View.GONE);
        mIsStart = true;
        setLivenessState(false);
        mFragment.resetStatus(true);
        noticeLinearLayout.setVisibility(View.VISIBLE);
        animFrame.setVisibility(View.VISIBLE);
        onLivenessDetectCallBack(mMotionList[0].getValue(), 0);
    }

    private void updateTheLastStepUI(ViewGroup viewGroup) {
        if (mDetectList.length >= 1
                && mDetectList.length <= imageResource.length) {
            imageResource[mDetectList.length - 1] = imageResourceSolid[mDetectList.length - 1];
            viewGroup.removeViewAt(mDetectList.length - 1);
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
            imageView.setImageResource(imageResource[mDetectList.length - 1]);
            viewGroup.addView(imageView, mDetectList.length - 1);
        } else if (mDetectList.length > imageResource.length) {
            imageResource[imageResource.length - 1] = imageResourceSolid[imageResource.length - 1];
            viewGroup.removeViewAt(imageResource.length - 1);
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
            imageView.setImageResource(imageResource[imageResource.length - 1]);
            viewGroup.addView(imageView, imageResource.length - 1);
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void updateUi(int stringId, int animationId, int number) {
        mNoteTextView.setText(getStringWithID(stringId));
        if (animationId != 0) {
            startAnimation(animationId);
        }
        if (number - 2 >= 0 && number - 1 < imageResource.length) {
            imageResource[number - 2] = imageResourceSolid[number - 2];
            viewGroup.removeViewAt(number - 2);
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
            imageView.setImageResource(imageResource[number - 2]);
            viewGroup.addView(imageView, number - 2);
        }
        playSoundNotice(number);
    }

    private void playSoundNotice(int step) {
        if (step > 0) {
            if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.blink))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_blink.mp3", false);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.nod))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_nod.mp3", false);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.mouth))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_mouth.mp3", false);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.yaw))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_yaw.mp3", false);
                }
            }
        }
    }

    public static void saveLivenessResult(byte[] livenessResult) {
        String resultPath = EXTRA_RESULT_PATH + LIVENESS_FILE_NAME;
        try {
            File file = new File(resultPath);
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            } else {
                file.createNewFile();
            }
            if (null != livenessResult) {
                writeLivenessResultFile(resultPath, livenessResult);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onLivenessDetectSuccess() {
        Intent intent = new Intent();
        intent.setClass(this, LivenessNoteActivity.class);
    }

    public void saveFinalEncryFile(byte[] livenessResult) {
        Intent intent = new Intent();
        if (mFragment.mDetector != null) {
            STFinanceJNI.CVFinanceFrame[] array = mFragment.getImageResult();
            if (array != null) {
                /*for(STFinanceJNI.CVFinanceFrame frame : array) {
                    intent.putExtra("motion" + frame.motion, frame.motion);
                    intent.putExtra("length" + frame.motion, frame.length);
                    intent.putExtra("image"+frame.motion, frame.image);
                }*/
                intent.putExtra("motion" + array[0].motion, array[0].motion);
                intent.putExtra("length" + array[0].motion, array[0].length);
                intent.putExtra("image" + array[0].motion, array[0].image);
                System.out.println("motion" + array[0].motion+"  :"+array[0].motion);
                System.out.println("length" + array[0].motion+"  :"+array[0].length);
                System.out.println("image" + array[0].motion+"  :"+array[0].image);

            }
            intent.putExtra("livenessResult", livenessResult);
            mFragment.mDetector.destroy();
            mFragment.mDetector = null;
        }
        if (livenessResult != null) {
            saveEncryFile(livenessResult);
        }
        if (livenessResult != null) {
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    public static void saveEncryFile(byte[] livenessResult) {
        if (livenessResult != null) {
            saveFile(livenessResult, EXTRA_RESULT_PATH, LIVENESS_FILE_NAME);
        }
    }

    /**
     * 根据byte数组，生成文件
     */
    public static void saveFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos  = null;
        FileOutputStream     fos  = null;
        File                 file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void writeLivenessResultFile(String path, byte[] content) throws IOException {
        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }

    private void showDialog(String title, String msg) {
        if (isDialogShowing()) {
            return;
        }
        if (mDetectList.length > 0) {
            viewGroup.removeAllViews();
        }
        if (mDetectList.length >= 1
                && mDetectList.length <= defaultImageResource.length) {
            for (int i = 0; i < mDetectList.length; i++) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
                imageView.setImageResource(defaultImageResource[i]);
                viewGroup.addView(imageView);
            }
        } else if (mDetectList.length > defaultImageResource.length) {
            for (int i = 0; i < defaultImageResource.length; i++) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
                imageView.setImageResource(defaultImageResource[i]);
                viewGroup.addView(imageView);
            }
        }
        setLivenessState(true);
        mTimeViewContoller.hide();
        mDialog = new LinkfaceAlertDialog(mContext).builder().setCancelable(false).
                setTitle(getStringWithID(R.string.linkface_failure_dialog_title)).setNegativeButton(getStringWithID(R.string.cancel), new View
                .OnClickListener() {
            @Override
            public void onClick(View arg0) {
                onErrorHappen(RESULT_CANCELED);
            }
        }).setPositiveButton(getStringWithID(R.string.restart_preview), new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mFragment.registerLivenessDetectCallback(listenerCallBack);
                restartAnimationAndLiveness();
            }
        });
        if (((Activity) mContext).isFinishing()) {
            return;
        }
        mDialog.show();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void restartAnimationAndLiveness() {
        mFragment.resetStatus(false);
        mFragment.setConfigAndstartDetect();
        setLivenessState(false);
        DataController.deleteFiles(EXTRA_RESULT_PATH);
        if (mDetectList.length >= 1) {
            imageResource[0] = imageResourceSolid[0];
            viewGroup.removeViewAt(0);
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.MATCH_PARENT));
            imageView.setImageResource(imageResource[0]);
            viewGroup.addView(imageView, 0);
        }
        startAnimation(CURRENT_ANIMATION);
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        restartPlaySoundNotice(currentDetectStep);
    }

    private void restartPlaySoundNotice(int step) {
        if (step > 0) {
            if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.blink))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_blink.mp3", true);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.nod))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_nod.mp3", true);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.mouth))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_mouth.mp3", true);
                }
            } else if (mDetectList[step - 1]
                    .equalsIgnoreCase(getString(R.string.yaw))) {
                stopAndRelease(mediaPlayer);
                if (soundNoticeOrNot) {
                    setMediaSource("linkface_notice_yaw.mp3", true);
                }
            }
        }
    }

    private boolean isDialogShowing() {
        if (mDialog == null || !mDialog.isShowing()) {
            return false;
        } else if (mDialog != null && mDialog.isShowing()) {
            return true;
        } else {
            return false;
        }
    }

    public void onErrorHappen(int resultCode) {
        setResult(resultCode);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(Constants.RESULT, "活体检测被取消!");
        intent.putExtras(bundle);
        setResult(RESULT_CANCELED, intent);
        finish();
    }

    private void restartPrepareAndPlay(MediaPlayer media) {
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();
        mediaPlayer.setLooping(true);
    }

    private void prepareAndPlay(MediaPlayer media) {
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (isDialogShowing()) {
            mediaPlayer.stop();
        } else {
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
        }
    }

    public void stopAndRelease(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void setMediaSource(String mediaName, boolean restart) {
        AssetManager        am             = this.getAssets();
        AssetFileDescriptor fileDescriptor = null;
        try {
            fileDescriptor = am.openFd(mediaName);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            if (restart) {
                restartPrepareAndPlay(mediaPlayer);
            } else {
                prepareAndPlay(mediaPlayer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (!mFragment.mPaused && mFragment.mDetector != null
                    && mFragment.createHandleSuccess) {
                if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                    try {
                        // add the MAGNETIC_FIELD info
                        mFragment.mDetector
                                .addSequentialInfo(
                                        LivenessDetector.WrapperSequentialInfo.MAGNETIC_FIELD
                                                .getValue(), event.values[0]
                                                + " " + event.values[1] + " "
                                                + event.values[2] + " ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                    try {
                        // add the ACCLERATION info
                        mFragment.mDetector
                                .addSequentialInfo(
                                        LivenessDetector.WrapperSequentialInfo.ACCLERATION
                                                .getValue(), event.values[0]
                                                + " " + event.values[1] + " "
                                                + event.values[2] + " ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
                    try {
                        // add the ROTATION_RATE info
                        mFragment.mDetector
                                .addSequentialInfo(
                                        LivenessDetector.WrapperSequentialInfo.ROTATION_RATE
                                                .getValue(), event.values[0]
                                                + " " + event.values[1] + " "
                                                + event.values[2] + " ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
                    try {
                        // add the GRAVITY info
                        mFragment.mDetector.addSequentialInfo(
                                LivenessDetector.WrapperSequentialInfo.GRAVITY
                                        .getValue(), event.values[0] + " "
                                        + event.values[1] + " "
                                        + event.values[2] + " ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
}
